﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PayloadTracker
{

    /// <summary>
    /// Class for loading and storing Flights.
    /// </summary>
    [Serializable]
    public class FlightCollection : IEnumerable<Flight>
    {
        List<Flight> m_Flights;
        public List<Flight> Flights
        {
            get { return m_Flights; }
            set { m_Flights = value; }
        }

        public FlightCollection()
        {
            m_Flights = new List<Flight>();
        }
        /// <summary>
        /// Save to file
        /// </summary>
        /// <param name="Filename"></param>
        public void Save(string Filename)
        {
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(FlightCollection));
            var writerSettings = new System.Xml.XmlWriterSettings();
            writerSettings.Indent = true;
            writerSettings.OmitXmlDeclaration = true;
            var writer = System.Xml.XmlWriter.Create(Filename, writerSettings);
            xmlSerializer.Serialize(writer, this);

            writer.Flush();
            writer.Close();
        }
        /// <summary>
        /// Load from file
        /// </summary>
        /// <param name="Filename"></param>
        public static FlightCollection Load(string Filename)
        {
            if (!System.IO.File.Exists(Filename))
            {
                Logger.LOG.WriteLine("FlightCollection does not exist creating new.");
                return new FlightCollection();
            }
            try
            {
                var xrs = new System.Xml.XmlReaderSettings();
                xrs.CloseInput = true;
                var xmlDeserializer = new System.Xml.Serialization.XmlSerializer(typeof(FlightCollection));
                using(var reader = System.Xml.XmlReader.Create(System.IO.File.OpenRead(Filename),xrs))
                    return xmlDeserializer.Deserialize(reader) as FlightCollection;
            }
            catch (System.Exception ex)
            {
                Logger.LOG.Error("Error loading FlightCollection data from: " + Filename + ". Due to " + ex.Message + " Creating new.");

                return new FlightCollection();
            }
        }


        #region IEnumerableMembers

        public void Add(object o)
        {
            if (o.GetType() != typeof(Flight))
                throw new Exception("Invalid type.");

            Flight f = ((Flight)o);

            m_Flights.Add(f);
            
        }
        public IEnumerator<Flight> GetEnumerator()
        {
            return m_Flights.GetEnumerator();
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return m_Flights.GetEnumerator();
        }

        #endregion
    }
}
